package core

import (
	"fmt"
	"io"
	"net"
	"openzbox.com/driver/host/nuvoton/nuc98x"
	log "openzbox.com/log"
	"openzbox.com/utils/scheduler"
	"os/exec"
	"strings"
	"time"
)

var UUIDPortName = "/dev/ttyS9"
var Port4GName = "/dev/ttyS5"

func asyncLog(reader io.ReadCloser) error {
	cache := "" //缓存不足一行的日志信息
	buf := make([]byte, 1024)
	for {
		num, err := reader.Read(buf)
		if err != nil && err != io.EOF {
			return err
		}
		if num > 0 {
			b := buf[:num]
			s := strings.Split(string(b), "\n")
			line := strings.Join(s[:len(s)-1], "\n") //取出整行的日志
			fmt.Printf("%s%s\n", cache, line)
			cache = s[len(s)-1]
		}
	}
	return nil
} /**/

func (box *Mbox) RunShellCommand(callcmd string) error {
	log.Info(callcmd)
	cmd := exec.Command("/bin/sh", "-c", callcmd) //不加第一个第二个参数会报错
	//cmd.Stdout = os.Stdout // cmd.Stdout -> stdout  重定向到标准输出，逐行实时打印
	//cmd.Stderr = os.Stderr // cmd.Stderr -> stderr
	//也可以重定向文件 cmd.Stderr= fd (文件打开的描述符即可)

	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()
	defer stdout.Close()
	defer stderr.Close()

	if err := cmd.Start(); err != nil {
		log.Errorf("Error starting command: %s......", err.Error())
		return err
	}

	go asyncLog(stdout)
	go asyncLog(stderr)

	if err := cmd.Wait(); err != nil {
		log.Errorf("Error waiting for command execution: %s......", err.Error())
		return err
	}
	return nil
}

/*
	看门狗喂狗
*/
func (mbox *Mbox) WDTKeepLive() error {
	f, ex := nuc98x.InitWDT()
	if ex == nil {
		scheduler.Every(5).Seconds().NotImmediately().Run(func() {
			err := nuc98x.WDTKeepLive(f)
			//mbox.updateBoxPortStatus()
			if err != nil {
				log.Error(err)
			}
		})
	} else {
		return ex
	}
	/*
		scheduler.Every(5).Seconds().NotImmediately().Run(func() {
			box.updateBoxPortStatus()
		})*/
	return nil
}

func (mbox *Mbox) Iamhere() {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return
	}
	var lip net.IP = nil
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			ipnet.Network()
			if ipnet.IP.To4() != nil {
				lip = ipnet.IP.To4()
			}
		}
	}
	ticker := time.NewTicker(time.Second * 30)
	go func() {
		for _ = range ticker.C {
			// 这里设置发送者的IP地址，自己查看一下自己的IP自行设定
			if lip != nil {
				laddr := net.UDPAddr{
					IP:   lip, // net.IPv4(192, 168, 137, 224),
					Port: 3000,
				}
				// 这里设置接收者的IP地址为广播地址
				raddr := net.UDPAddr{
					IP:   net.IPv4(255, 255, 255, 255),
					Port: 3000,
				}
				conn, err := net.DialUDP("udp", &laddr, &raddr)
				if err != nil {
					println(err.Error())
					return
				}
				conn.Write([]byte(fmt.Sprintf("%s,%s,%s\r\n", mbox.Name, mbox.ID, lip)))
				conn.Close()
			}
		}
	}()

}
